package com.lagou.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.jfinal.kit.HttpKit;
import com.lagou.commons.PayConfig;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@RestController
@RequestMapping("pay")
@CrossOrigin
public class WxPayController {

    @GetMapping("createCode")
    public Object createCode(String courseid,String coursename,String price) throws Exception {

        coursename = new String(coursename.getBytes("ISO-8859-1"),"UTF-8");

        //编写商户信息写入到map中
        Map<String,String> map = new HashMap<>();
        map.put("appid", PayConfig.appid); //公众账号ID，微信分配的公众账号ID（企业号corpid即为此appid）
        map.put("mch_id",PayConfig.partner); //商户号，微信支付分配的商户号
        map.put("nonce_str", WXPayUtil.generateNonceStr()); //随机字符串，不长于32位
        map.put("body",coursename); //商品的描述，这里就传递对应的课程名称
        map.put("out_trade_no",WXPayUtil.generateNonceStr()); //随机生成的商户订单号
        map.put("total_fee",price); //订单金额，说明：订单总金额，单位为分，只能为整数
        map.put("spbill_create_ip","127.0.0.1");
        map.put("notify_url",PayConfig.notifyurl); //通知地址（回调URL）
        map.put("trade_type","NATIVE"); //交易类型

        System.out.println("商户信息：" +map);

        //生成数字签名，并把商户信息转换成xml格式
        String xml = WXPayUtil.generateSignedXml(map, PayConfig.partnerKey);

        System.out.println("商户的xml信息：" +xml);

        //将xml数据发送给微信支付平台，从而生成订单
        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        //发送请求，并返回一个xml格式的字符串
        String post = HttpKit.post(url, xml); //将对应的xml信息给微信支付平台（因为一般他们通常操作xml信息）

        System.out.println(post);
        //到这里，由于是测试数据，那么基本会显示


        //微信支付平台返回xml格式的数据，将其转换成map格式并返回给前端
        Map<String, String> map1 = WXPayUtil.xmlToMap(post);
        map1.put("orderId",map.get("out_trade_no"));

        System.out.println(map1);


        return map1;
    }

    @GetMapping("checkOrderStatus")
    public Object createCode(String orderId) throws Exception {

        //编写商户信息
        Map<String,String> map = new HashMap<>();
        map.put("appid", PayConfig.appid); //公众账号ID，微信分配的公众账号ID（企业号corpid即为此appid）
        map.put("mch_id",PayConfig.partner); //商户号，微信支付分配的商户号
        map.put("out_trade_no", orderId); //商户订单号
        map.put("nonce_str",WXPayUtil.generateNonceStr()); //随机字符串，不长于32位
        System.out.println(orderId);

        String xml = WXPayUtil.generateSignedXml(map, PayConfig.partnerKey);

        //发送查询请求给微信支付平台
        String url = "https://api.mch.weixin.qq.com/pay/orderquery";

        //设置订单状态的开始时间点
        long l = System.currentTimeMillis();

        //不停的去微信支付平台询问是否支付成功
        while(true) {
//            String post = HttpKit.post(url, xml);
//
//            //对微信支付平台返回的查询结果进行处理
//            Map<String, String> map1 = WXPayUtil.xmlToMap(post);
//return null;
////            if(map1.get("trade_state").equalsIgnoreCase("SUCCESS")) {
////                return map1;
////            }
//
//
////            if(System.currentTimeMillis() - l>30*1000){
////                return map1;
////            }
//            Thread.sleep(10000);
            return null;
        }

    }

    @RequestMapping("wxCallback")
    public String wxCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        InputStream inStream = null;
        ByteArrayOutputStream outSteam = null;
        String resultxml = null;
        try {
            inStream = request.getInputStream();
            outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            resultxml = new String(outSteam.toByteArray(), "utf-8");
        } catch (Exception e) {
            System.out.println("回调处理失败");
        }finally {
            if(null != outSteam) {
                outSteam.close();
            }
            if(null != inStream) {
                inStream.close();
            }
        }
        System.out.println("wxCallback - 回调请求参数:"+ resultxml);
        return resultxml;
    }

}